package com.hyper_yang._05_juc.chap03;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

//资源类
//线程间通信：
//synchronized  - wait/notify/notifyAll
//Lock  - Condition（await/signal/signalAll）
class ShareDataTwo extends Object {
    private int number = 0;

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    //加
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //判断
            //if(number==1){ //由于if判断，导致虚假唤醒。所以，不能使用if判断。
            while (number != 0) { // 使用while代替if进行判断，可以避免虚假唤醒。
                condition.await();
            }

            //干活
            number++;
            System.out.println(Thread.currentThread().getName() + " number = " + number);

            //通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    //减
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (number != 1) {
                condition.await();
            }

            //干活
            number--;
            System.out.println(Thread.currentThread().getName() + " number = " + number);

            //通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 多线程模板（上）
 * 高内聚、低耦合   线程 操作 资源类
 * 多线程模板（中）
 * 判断   干活   通知
 * 多线程模板(下)
 * while代替if判断，避免虚假唤醒。
 * <p>
 * 需求：两个线程操作一个初始值为0的变量，实现一个线程对变量增加1，一个线程对变量减少1，交替10轮。
 */
public class LockConditionDemo {
    public static void main(String[] args) {
        ShareDataTwo shareDataTwo = new ShareDataTwo();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    shareDataTwo.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    shareDataTwo.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();


        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    shareDataTwo.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    shareDataTwo.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}
